﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.demo.IRepositories.Outbound;
using VOL.demo.IServices.Outbound;
using VOL.Entity.DomainModels;

namespace VOL.demo.Services.Outbound
{
    /// <summary>
    /// 出库单服务实现
    /// </summary>
    public class OutboundService : IOutboundIService
    {
        private readonly IOutboundRepository _repository;

        public OutboundService(IOutboundRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 获取出入库类型下拉列表
        /// </summary>
        /// <returns>出入库类型列表</returns>
        public async Task<List<InOutTypeDto>> GetInOutTypeListAsync()
        {
            try
            {
                return await _repository.GetInOutTypeListAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetInOutTypeListAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 获取仓库下拉列表
        /// </summary>
        /// <returns>仓库列表</returns>
        public async Task<List<WarehouseDto>> GetWarehouseListAsync()
        {
            try
            {
                return await _repository.GetWarehouseListAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetWarehouseListAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <returns>用户列表</returns>
        public async Task<List<UserDto>> GetUserListAsync()
        {
            try
            {
                return await _repository.GetUserListAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetUserListAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 根据出入库类型ID分页查询销售订单（多表联查）
        /// </summary>
        /// <param name="inOutTypeId">出入库类型ID</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="orderCode">订单编号（可选）</param>
        /// <param name="customerName">客户名称（可选）</param>
        /// <returns>分页结果</returns>
        public async Task<(List<SalesOrderDto> Data, int TotalCount)> GetSalesOrderPageListAsync(
            long inOutTypeId,
            int pageIndex,
            int pageSize,
            string orderCode = null,
            string customerName = null)
        {
            try
            {
                // 页码从1开始，但SqlSugar分页从0开始，需要转换
                int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;

                // 调用仓储层方法
                return await _repository.GetSalesOrderPageListAsync(inOutTypeId, sqlSugarPageIndex, pageSize, orderCode, customerName);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetSalesOrderPageListAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 根据出入库类型ID分页查询进货退货（多表联查）
        /// </summary>
        /// <param name="inOutTypeId">出入库类型ID</param>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="returnOrderCode">退货单号（可选）</param>
        /// <param name="supplierName">供应商名称（可选）</param>
        /// <returns>分页结果</returns>
        public async Task<(List<ReturnOrderDto> Data, int TotalCount)> GetReturnOrderPageListAsync(
            long inOutTypeId,
            int pageIndex,
            int pageSize,
            string returnOrderCode = null,
            string supplierName = null)
        {
            try
            {
                // 页码从1开始，但SqlSugar分页从0开始，需要转换
                int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;

                // 调用仓储层方法
                return await _repository.GetReturnOrderPageListAsync(inOutTypeId, sqlSugarPageIndex, pageSize, returnOrderCode, supplierName);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetReturnOrderPageListAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 根据销售订单ID查询销售订单明细（与货品表联查）
        /// </summary>
        /// <param name="shopOrderId">销售订单ID</param>
        /// <returns>销售订单明细列表</returns>
        public async Task<List<SalesOrderDetailDto>> GetSalesOrderDetailsByIdAsync(long shopOrderId)
        {
            try
            {
                return await _repository.GetSalesOrderDetailsByIdAsync(shopOrderId);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetSalesOrderDetailsByIdAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 根据退货订单ID查询退货订单明细（与进货明细表和货品表联查）
        /// </summary>
        /// <param name="returnOrderId">退货订单ID</param>
        /// <returns>退货订单明细列表</returns>
        public async Task<List<ReturnOrderDetailDto>> GetReturnOrderDetailsByIdAsync(long returnOrderId)
        {
            try
            {
                return await _repository.GetReturnOrderDetailsByIdAsync(returnOrderId);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetReturnOrderDetailsByIdAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 退货出库（事务性操作）
        /// </summary>
        /// <param name="request">退货出库请求</param>
        /// <returns>出库单ID</returns>
        public async Task<long> CreateReturnOutboundAsync(ReturnOutboundRequestDto request)
        {
            try
            {
                // 参数验证
                if (request == null)
                {
                    throw new ArgumentException("退货出库请求不能为空");
                }

                if (string.IsNullOrWhiteSpace(request.OutboundCode))
                {
                    throw new ArgumentException("出库编号不能为空");
                }

                if (request.Details == null || request.Details.Count == 0)
                {
                    throw new ArgumentException("出库明细不能为空");
                }

                // 验证出库数量和明细ID
                foreach (var detail in request.Details)
                {
                    if (detail.DetailId <= 0)
                    {
                        throw new ArgumentException($"退货明细ID必须大于0，明细ID: {detail.DetailId}");
                    }
                    if (detail.OneOutboundNum <= 0)
                    {
                        throw new ArgumentException($"出库数量必须大于0，明细ID: {detail.DetailId}");
                    }
                }

                Console.WriteLine($"=== OutboundService.CreateReturnOutboundAsync开始 ===");
                Console.WriteLine($"出库编号: {request.OutboundCode}, 明细数量: {request.Details.Count}");

                // 调用仓储层方法
                var outboundId = await _repository.CreateReturnOutboundAsync(request);

                Console.WriteLine($"✅ 退货出库成功，出库单ID: {outboundId}");
                return outboundId;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.CreateReturnOutboundAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 销售订单出库（事务性操作）
        /// </summary>
        /// <param name="request">销售订单出库请求</param>
        /// <returns>出库单ID</returns>
        public async Task<long> CreateSalesOutboundAsync(SalesOutboundRequestDto request)
        {
            try
            {
                // 参数验证
                if (request == null)
                {
                    throw new ArgumentException("销售订单出库请求不能为空");
                }

                if (string.IsNullOrWhiteSpace(request.OutboundCode))
                {
                    throw new ArgumentException("出库编号不能为空");
                }

                if (request.Details == null || request.Details.Count == 0)
                {
                    throw new ArgumentException("出库明细不能为空");
                }

                // 验证出库数量和明细ID
                foreach (var detail in request.Details)
                {
                    if (detail.DetailId <= 0)
                    {
                        throw new ArgumentException($"销售订单明细ID必须大于0，明细ID: {detail.DetailId}");
                    }
                    if (detail.OneOutboundNum <= 0)
                    {
                        throw new ArgumentException($"出库数量必须大于0，明细ID: {detail.DetailId}");
                    }
                }

                Console.WriteLine($"=== OutboundService.CreateSalesOutboundAsync开始 ===");
                Console.WriteLine($"出库编号: {request.OutboundCode}, 明细数量: {request.Details.Count}");

                // 调用仓储层方法
                var outboundId = await _repository.CreateSalesOutboundAsync(request);

                Console.WriteLine($"✅ 销售订单出库成功，出库单ID: {outboundId}");
                return outboundId;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.CreateSalesOutboundAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 分页查询出库单（多表联查）
        /// </summary>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="outboundCode">出库编号（可选）</param>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>分页结果</returns>
        public async Task<(List<OutboundDto> Data, int TotalCount)> GetPageListWithRelationsAsync(
            int pageIndex,
            int pageSize,
            string outboundCode = null,
            long? userId = null)
        {
            try
            {
                // 页码从1开始，但SqlSugar分页从0开始，需要转换
                int sqlSugarPageIndex = pageIndex <= 0 ? 0 : pageIndex - 1;

                // 调用仓储层方法
                return await _repository.GetPageListWithRelationsAsync(sqlSugarPageIndex, pageSize, outboundCode, userId);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetPageListWithRelationsAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }
        /// <summary>
        /// 根据出库ID查询出库明细列表（多表联查）
        /// </summary>
        /// <param name="outboundId">出库单ID</param>
        /// <returns>出库明细列表</returns>
        public async Task<List<OutboundDetailDto>> GetOutboundDetailsByIdAsync(long outboundId)
        {
            try
            {
                // 参数验证
                if (outboundId <= 0)
                {
                    throw new ArgumentException("出库单ID必须大于0");
                }

                Console.WriteLine($"=== OutboundService.GetOutboundDetailsByIdAsync开始 ===");
                Console.WriteLine($"出库单ID: {outboundId}");

                // 调用仓储层方法
                var result = await _repository.GetOutboundDetailsByIdAsync(outboundId);

                Console.WriteLine($"✅ 查询出库明细成功，数量: {result.Count}");
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ OutboundService.GetOutboundDetailsByIdAsync异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                throw;
            }
        }
    }
}
